<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="120px">
      <el-form-item
        label=""
        prop="billingModelName">
        <el-input
          v-model="queryParams.billingModelName"
          placeholder="请输入计费模型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label=""
        prop="protocolName">
        <el-select v-model="queryParams.protocolName" placeholder="请选择适用协议类型" clearable>
          <el-option
            v-for="protocolType in protocolTypeList"
            :key="protocolType.key"
            :label="protocolType.value"
            :value="protocolType.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label=""
        prop="billingModelStageType">
        <el-select v-model="queryParams.billingModelStageType" placeholder="请选择计费分段类型" clearable>
          <el-option
            v-for="stageType in stageTypeList"
            :key="stageType.key"
            :label="stageType.value"
            :value="stageType.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery">搜索
        </el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery">重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:model:add']"
        >新增
        </el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:model:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:model:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:model:export']"
        >导出
        </el-button>
      </el-col>-->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="modelList"
      @selection-change="handleSelectionChange"
      :stripe="true">
      <el-table-column
        label="计费模型名称"
        align="center"
        prop="billingModelName"/>
      <el-table-column
        label="计费分段类型"
        align="center"
        prop="billingModelStageType">
        <template slot-scope="scope">
          <el-tag :type="scope.row.billingModelStageType == 'T' ? 'success' : ''">
            {{ scope.row.billingModelStageType == 'T' ? '分时电价' : '阶梯功率' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="适用协议类型"
        align="center"
        prop="protocolName"/>
      <el-table-column
        label="时段划分总段数"
        align="center"
        prop="stageNum"/>
      <el-table-column
        label="绑定设备总数"
        align="center"
        prop="deviceCount"/>
      <el-table-column
        label="默认值标志"
        align="center"
        prop="defaultModel">
        <template slot-scope="scope">
          <el-tag effect="dark" :type="scope.row.billingModelStageType == 'T' ? 'success' : ''">
            {{ scope.row.defaultModel == '1' ? '默认' : '新建' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            :class="['text-button', { 'active': active===scope.$index+'handleBind' }]"
            type="text"
            @click="handleBind(scope.row),active=scope.$index+'handleBind'"
            icon="el-icon-setting"
            v-hasPermi="['business:model:setting']"
          >绑定设备
          </el-button>
          <el-button
            size="mini"
            :class="['text-button', { 'active': active===scope.$index+'handleUpdate' }]"
            type="text"
            @click="handleUpdate(scope.row),active=scope.$index+'handleUpdate'"
            icon="el-icon-edit"
            v-hasPermi="['business:model:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:model:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改计费模型对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="70%"
      append-to-body>
      <div style="display: flex;flex-direction: row;justify-content: space-between">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="130px"
        :inline="true">
<!--        <div style="margin-bottom: 20px; border-bottom: 1px solid #dedde3;">
          <el-form-item
            label="计费模式"
          >
            <el-select
              v-model="typeAll"
              @change="changeTypeList"
              placeholder="请选择计费模式">
              <el-option
                v-for="(item, index) in typeList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>-->

<!--        <el-form-item
          label="设备类型"
          prop="deviceType">
          <el-select
            v-model="form.deviceType"
            placeholder="请选择">
            <el-option
              v-for="(deviceType, index) in deviceTypeList"
              :key="index"
              :label="deviceType.label"
              :value="deviceType.value"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item
          label="计费模型名称"
          prop="billingModelName">
          <el-input
            :disabled="form.defaultModel === 1"
            v-model="form.billingModelName"
            placeholder="请输入计费模型名称"/>
        </el-form-item>
        <el-form-item
          label="适用协议类型"
          prop="protocolName">
          <el-select v-model="form.protocolName" placeholder="请选适用协议类型" clearable>
            <el-option
              v-for="protocolType in protocolTypeList"
              :key="protocolType.key"
              :label="protocolType.value"
              :value="protocolType.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="计费分段类型"
          prop="billingModelStageType">
          <el-select v-model="form.billingModelStageType" placeholder="请选计费分段类型" clearable>
            <el-option
              v-for="stageType in stageTypeList"
              :key="stageType.key"
              :label="stageType.value"
              :value="stageType.key"
            />
          </el-select>
        </el-form-item>
      </el-form>
        <el-button v-if="form.billingModelStageType == 'T'" style="height: 36px" size="small" type="success" @click="addDomain">新增区间</el-button>
      </div>
      <el-table
        v-if="form.billingModelStageType == 'T'"
        v-loading="loading"
        :data="modelDataList"
        @selection-change="handleSelectionChange">

        <el-table-column
          label="顺序号"
          align="center"
          prop="sortNum"/>
        <el-table-column
          label="起始时间"
          align="center"
          prop="beginDuration">
          <template slot-scope="scope">
            <el-time-select
              :clearable="false"
              :editable="false"
              :disabled="scope.$index===0"
              v-model="scope.row.startTime"
              :picker-options="scope.row.pickerOptions"
              @change="timeChange($event,scope.$index)"
              placeholder="选择时间">
            </el-time-select>
          </template>
        </el-table-column>
        <el-table-column
          label="服务费"
          align="center"
          prop="serviceFee">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.serviceFee"
              placeholder="请输入服务费"
              oninput="value=value.replace(/[^\d.]/g,'')"/>
          </template>
        </el-table-column>
        <el-table-column
          label="电价"
          align="center"
          prop="electricityPrice">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.electricityPrice"
              placeholder="请输入电价"
              oninput="value=value.replace(/[^\d.]/g,'')"/>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          prop="electricityPrice">
          <template slot-scope="scope">
            <el-button v-if="scope.$index>0" @click="handleDomain(scope.$index)" type="primary" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-table
        v-if="form.billingModelStageType == 'P'"
        v-loading="loading"
        :data="modelDataList2"
        @selection-change="handleSelectionChange">

        <el-table-column
          label="顺序号"
          align="center"
          prop="sortNum"/>
        <el-table-column
          label="阶段最大功率（单位：W）"
          align="center"
          prop="beginDuration">
          <template slot-scope="scope">

            <el-input-number v-model="scope.row.beginDuration" @change="handleChangePower($event,scope.$index)" :step="50" :min="scope.row.min" :max="999999" label=""></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          label="服务费（元）"
          align="center"
          prop="serviceFee">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.serviceFee"
              placeholder="请输入服务费"
              oninput="value=value.replace(/[^\d.]/g,'')"/>
          </template>
        </el-table-column>
        <el-table-column
          label="电价（元/小时）"
          align="center"
          prop="electricityPrice">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.electricityPrice"
              placeholder="请输入电价"
              oninput="value=value.replace(/[^\d.]/g,'')"/>
          </template>
        </el-table-column>
      </el-table>
      <div
        slot="footer"
        class="dialog-footer">
        <el-button
          type="primary"
          :loading="bthLoading"
          @click="submitForm">确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择站场设备对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="openBind"
      @open="openFor"
      width="1000px"
      append-to-body>
      <el-row :gutter="24">
        <el-col
          :span="14"
          :xs="24">
          <div style="padding-bottom: 10px">计费模式</div>
          <el-table
            border
            v-loading="loading"
            :data="timeList"
            >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              prop="index"/>
            <el-table-column
              v-if="typeAll == 'T'"
              label="起始时间"
              align="center"
              prop="beginDuration">
              <template slot-scope="scope">
                {{ scope.row.beginDuration | getH }}
              </template>
            </el-table-column>
            <el-table-column
              v-if="typeAll == 'P'"
              label="阶段最大功率（单位：W）"
              align="center"
              prop="beginDuration">
              <template slot-scope="scope">
                {{ scope.row.beginDuration}}
              </template>
            </el-table-column>
            <el-table-column
              label="服务费(元)"
              align="center"
              prop="deviceType">
              <template slot-scope="scope">
                {{ scope.row.serviceFee | getPrice}}
              </template>
            </el-table-column>
            <el-table-column
              label="电价(元)"
              align="center"
              prop="electricityPrice">
              <template slot-scope="scope">
                {{ scope.row.electricityPrice | getPrice}}
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col
          :span="10"
          :xs="24">
          <div style="padding-bottom: 5px">选择场站设备</div>
          <div style="height: 420px; overflow: auto">
            <el-tree
              class="tree-border"
              :data="deviceOptions"
              show-checkbox
              ref="device"
              node-key="id"
              :default-checked-keys="checkedkeys"
              :check-strictly="false"
              empty-text="加载中，请稍候"
              :props="defaultProps"
            ></el-tree>
          </div>

        </el-col>
      </el-row>
      <div
        slot="footer"
        class="dialog-footer">
        <el-button
          type="primary"
          @click="submitBind">确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listModel, getModel, delModel, addModel, updateModel, getDeviceType, getAllDevice, bindModel , getProtocolList } from '@/api/business/model'
import { ChangeHourMinutestr, ChangeStrToMinutes } from '@/utils/common'

/*const modelDataList = [{ sortNum: 1, beginDuration: 0, startTime: '00:00', pickerOptions: { start: '00:00', step: '00:30', end: '18:00' }, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 2, beginDuration: 120, startTime: '02:00', pickerOptions: { start: '00:30', step: '00:30', end: '18:30' }, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 3, beginDuration: 240, startTime: '04:00', pickerOptions: { start: '02:30', step: '00:30', end: '19:00' }, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 4, beginDuration: 360, startTime: '06:00', pickerOptions: { start: '04:30', step: '00:30', end: '19:30' }, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 5, beginDuration: 480, startTime: '08:00', pickerOptions: { start: '06:30', step: '00:30', end: '20:00' }, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 6, beginDuration: 600, startTime: '10:00', pickerOptions: { start: '08:30', step: '00:30', end: '20:30' }, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 7, beginDuration: 720, startTime: '12:00', pickerOptions: { start: '10:30', step: '00:30', end: '21:00' }, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 8, beginDuration: 840, startTime: '14:00', pickerOptions: { start: '12:30', step: '00:30', end: '21:30' }, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 9, beginDuration: 960, startTime: '16:00', pickerOptions: { start: '14:30', step: '00:30', end: '22:00' }, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 10, beginDuration: 1080, startTime: '18:00', pickerOptions: { start: '16:30', step: '00:30', end: '22:30' }, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 11, beginDuration: 1200, startTime: '20:00', pickerOptions: { start: '18:30', step: '00:30', end: '23:00' }, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 12, beginDuration: 1320, startTime: '22:00', pickerOptions: { start: '20:30', step: '00:30', end: '23:30' }, serviceFee: 0, electricityPrice: 0 }]*/
const modelDataList = [{ sortNum: 1, beginDuration: 0, startTime: '00:00', pickerOptions: { start: '00:00', step: '00:30', end: '23:30' }, serviceFee: 0, electricityPrice: 0 }]
const modelDataList2 = [
  { sortNum: 1, beginDuration: 0, min: 0, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 2, beginDuration: 250, min: 50, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 3, beginDuration: 500, min: 100, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 4, beginDuration: 750, min: 150, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 5, beginDuration: 1000, min: 200, serviceFee: 0, electricityPrice: 0 },
  { sortNum: 6, beginDuration: 1250, min: 250, serviceFee: 0, electricityPrice: 0 }]
const serviceFeeType = [{ label: '按度数', value: 1 }, { label: '按每半小时', value: 2 }]
export default {
  name: 'Model',
  data () {
    const moneyReg = (rule, value, callback) => {
      if (value.length > 10) {
        callback(new Error('长度在 0 到 10 个字符'))
      } else {
        setTimeout(() => {
          if (!/^\d+[.]?\d{0,2}$/.test(value) && value) {
            callback(new Error('请输入正整数或小数保留两位小数'))
          } else {
            callback()
          }
        }, 500)
      }

    }
    return {
      active: null,
      bthLoading: false,
      serviceFeeType,
      resultObj: null,
      deviceTypeList: [],
      modelDataList: [],
      modelDataList2: [],
      protocolTypeList: [],
      stageTypeList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 计费模型表格数据
      modelList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        billingModelName: null,
        billingModelStageType:null,
        protocolName:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        billingModelName: [
          { required: true, message: '计费模型名称不能为空', trigger: 'blur' }
        ],
        billingModelStageType: [
          { required: true, message: '计费分段类型不能为空', trigger: 'change' }
        ],
        protocolName: [
          { required: true, message: '适用协议类型不能为空', trigger: 'change' }
        ]
      },
      modelId: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      deviceOptions: [],
      openBind: false,
      timeList: [],
      checkedkeys: [],
      typeAll: 'T',
      typeList: [{
        label: '时间计费',
        value: 'T'
      },{
        label: '功率计费',
        value: 'P'
      }]
    }
  },
  created () {
    this.getList()
    this.getDeviceType()
    this.getProtocolList()
  },
  filters: {
    getH (val) {
      return ChangeHourMinutestr(val)
    },
    getPrice(val) {
      return (val/100).toFixed(2)
    }
  },
  methods: {
    async getProtocolList(){
      let res = await getProtocolList()
      res.data.protocolTypeList.forEach(item=>{
        for (const [key, value] of Object.entries(item)) {
          this.protocolTypeList.push({
            key,value
          })
        }
      })
      res.data.stageTypeList.forEach(item=>{
        for (const [key, value] of Object.entries(item)) {
          this.stageTypeList.push({
            key,value
          })
        }
      })
    },
    async getDeviceType () {
      let res = await getDeviceType()
      this.resultObj = res.data.reduce((obj, item) => {
        this.deviceTypeList.push({
          label: Object.values(item)[0],
          value: Object.keys(item)[0]
        })
        Object.assign(obj, item)
        return obj
      }, {})
    },
    /** 查询计费模型列表 */
    getList () {
      this.loading = true
      listModel(this.queryParams).then(response => {
        this.modelList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.openBind = false
      this.checkedkeys = []
      this.reset()
      this.modelDataList = []
    },
    // 表单重置
    reset () {
      this.form = {
        billingModelId: null,
        deviceType: null,
        serviceFeeTop: null,
        serviceFeeType: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      const modelDataList = [{ sortNum: 1, beginDuration: 0, startTime: '00:00', pickerOptions: { start: '00:00', step: '00:30', end: '23:30' }, serviceFee: 0, electricityPrice: 0 }]
      this.reset()
      this.modelDataList = modelDataList
      this.modelDataList2 = modelDataList2
      this.open = true
      this.title = '添加计费模型'
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset()
      this.modelDataList = modelDataList
      this.modelDataList2 = modelDataList2
      const id = row.id || this.ids
      getModel(id).then(response => {
        this.form = response.data.billingModel
        this.handleBillModel(response.data.billingModelStageList)
        this.typeAll = response.data.billingModel.billingModelStageType
        this.open = true
        this.title = '修改计费模型'
      })
    },
    addDomain(){
      if (this.modelDataList.length>=8) {
        this.$message.error("不能添加超过8条");
        return
      }
      if (this.modelDataList[this.modelDataList.length-1].beginDuration >=1410) {
        this.$message.error("最后一组数据为'23:30'不能添加新的时间区间");
        return
      }
      //设置新数据
      let mode = JSON.parse(JSON.stringify(this.modelDataList[this.modelDataList.length-1]));
      mode.sortNum = this.modelDataList.length+1
      mode.beginDuration =  this.modelDataList[this.modelDataList.length-1].beginDuration + 30
      mode.startTime = ChangeHourMinutestr(mode.beginDuration)

      //修改旧数据
      this.modelDataList[this.modelDataList.length-1].pickerOptions.end = ChangeHourMinutestr(mode.beginDuration - 30)
      this.modelDataList.push(mode)
    },
    handleDomain(index){
      this.modelDataList.splice(index, 1)
      this.modelDataList.forEach((item,num)=>{
        item.sortNum = num+1
      })
    },
    handleBillModel (list) {
      list.forEach((item,index)=>{
        //Object.assign(this.modelDataList[index],item)
        item.startTime = ChangeHourMinutestr(item.beginDuration)
        item.electricityPrice = item.electricityPrice / 100
        item.serviceFee = item.serviceFee / 100
        let itemIndex = 0
        if (index > 0) itemIndex = index - 1
        item.pickerOptions = { start: list[itemIndex].startTime, step: '00:30', end: '23:30' }
      })
      this.modelDataList = list
      this.modelDataList2.forEach((item,index)=>{
        Object.assign(item,list[index])
        //item.electricityPrice = item.electricityPrice
        //item.serviceFee = item.serviceFee
      })
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.bthLoading=true
          let copyList = JSON.parse(JSON.stringify(this.form.billingModelStageType == 'P'?this.modelDataList2:this.modelDataList))
          copyList.forEach(item => {
            item.serviceFee = Math.round((item.serviceFee * 100))
            item.electricityPrice = Math.round((item.electricityPrice * 100))
          })
          this.form.billingModelStageList = copyList
          if (this.form.id != null) {
            updateModel(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.bthLoading=false
              this.open = false
              this.getList()
            })
          } else {
            addModel(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.bthLoading=false
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除计费模型编号为"' + ids + '"的数据项？').then(function () {
        return delModel(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('business/model/export', {
        ...this.queryParams
      }, `model_${new Date().getTime()}.xlsx`)
    },
    /** 时间替换 **/
    timeChange (e, index) {
      this.modelDataList[index].beginDuration = ChangeStrToMinutes(e)
      this.recurrence(e, index)
    },
    recurrence (e, index) {
      if (index >= this.modelDataList.length - 1) return
      this.modelDataList[index + 1].pickerOptions.start = ChangeHourMinutestr(this.modelDataList[index].beginDuration + 30)
      if (this.modelDataList[index].beginDuration >= this.modelDataList[index + 1].beginDuration) {
        this.modelDataList[index + 1].beginDuration = this.modelDataList[index].beginDuration + 30
        this.modelDataList[index + 1].startTime = ChangeHourMinutestr(this.modelDataList[index + 1].beginDuration)
        return this.recurrence(ChangeHourMinutestr(this.modelDataList[index + 1].beginDuration), index + 1)
      }
      return
    },
    recurrence2 (e, index) {
      if (index >= this.modelDataList2.length - 1) return
      if (this.modelDataList2[index].beginDuration >= this.modelDataList2[index + 1].beginDuration) {
        this.modelDataList2[index + 1].beginDuration = this.modelDataList2[index + 1].beginDuration + 50
        return this.recurrence2((this.modelDataList2[index + 1].beginDuration), index + 1)
      }
      if (this.modelDataList2[index].beginDuration <= this.modelDataList2[index - 1].beginDuration) {
        this.modelDataList2[index - 1].beginDuration = this.modelDataList2[index - 1].beginDuration - 50
        return this.recurrence2((this.modelDataList2[index - 1].beginDuration), index - 1)
      }
      return
    },
    handleChangePower(e, index) {
      this.recurrence2(e, index)
    },
    openFor() {
      //this.checkedkeys = []
    },
    /** 绑定设备弹出框 */
    handleBind (row) {
      this.checkedkeys = []
      this.modelId = row.id
      getModel(this.modelId).then(response => {
        this.timeList = response.data.billingModelStageList
        this.typeAll = response.data.billingModel.billingModelStageType
      })

      //this.timeList = row.billingModelStageList
      this.title = '设备绑定'
      getAllDevice().then(res => {
        this.openBind = true
        let refArray = res.data.map((obj, key) => {
          if(obj.devices.length>0) {
            obj.devices.forEach(item=>{
              if(this.modelId == item.billingModelId) {
                this.checkedkeys.push(item.deviceId)
              }

            })
          }
          let rObj = {}
          rObj.id = obj.id
          rObj.label = obj.stationName
          if (obj.devices.length > 0) {
            rObj.children = this.getChildren(obj.devices)
          } else {
            rObj.disabled = true
          }
          return rObj
        })
        this.deviceOptions = refArray
      })
    },
    getChildren (arr) {
      let refArray = arr.map((obj, key) => {
        let rObj = {}
        rObj.id = obj.deviceId
        rObj.label = obj.deviceName
        return rObj
      })
      return refArray
    },
    submitBind () {
      const bindParams = {}
      let Keys = this.getDeptAllCheckedKeys()
      if (Keys.length == 0) {
        this.$modal.msgError('请选择一个或多个设备')
        return false
      }
      let deviceIds = []
      Keys.forEach(item => {
        if (!item.hasOwnProperty('children')) {
          deviceIds.push(item.id)
        }
      })
      bindParams.deviceIds = deviceIds
      bindParams.billingModelId = this.modelId
      bindModel(bindParams).then(res => {
        this.$modal.msgSuccess('绑定成功')
        this.openBind = false
      })
    },
    getDeptAllCheckedKeys () {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.device.getCheckedNodes()
      return checkedKeys
    }

  }
}
</script>
<style scoped>
/deep/.el-dialog__body {
  padding: 0 20px;
}
</style>
